package com.example.weathermvvm.data

import com.example.weathermvvm.data.db.PlaceDao
import com.example.weathermvvm.data.network.api.WeatherNetwork
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 *
 * @Author： LJH
 * @Time： 2022/8/10
 * @description：Place仓库，获取数据库或者网络接口的place数据
 */
class PlaceRepository private constructor(private val placeDao: PlaceDao,private val network: WeatherNetwork){

    suspend fun getProvinces() = withContext(Dispatchers.IO){
        var list = placeDao.getProvinces()
        if (list.isEmpty()){
            list = network.fetchProvinceList()
            placeDao.saveProvinceList(list)
        }
        list
    }

    suspend fun getCities(provinceId : Int) = withContext(Dispatchers.IO){
        var list = placeDao.getCities(provinceId)
        if (list.isEmpty()){
            list = network.fetchCityList(provinceId)
            list.forEach { it.provinceId = provinceId }
            placeDao.saveCityList(list)
        }
        list
    }

    suspend fun getCounties(provinceId: Int,cityCode:Int) = withContext(Dispatchers.IO){
        var list = placeDao.getCounties(cityCode)
        if (list.isEmpty()){
            list = network.fetchCounties(provinceId,cityCode)
            list.forEach { it.cityId = cityCode }
            placeDao.saveCountyList(list)
        }
        list
    }

    companion object{
        private var instance:PlaceRepository? = null
        fun getInstance(placeDao: PlaceDao,network: WeatherNetwork):PlaceRepository{
            if (instance == null){
                synchronized(PlaceRepository::class.java){
                    if (instance == null){
                        instance = PlaceRepository(placeDao, network)
                    }
                }
            }
            return instance!!
        }
    }
}